import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/page/subscription/api/api_subscription.dart';
import 'package:tender_flutter/page/subscription/model/subscript_category_entity.dart';
import 'package:tender_flutter/page/subscription/model/subscription_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/picker.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/progress_indicator.dart';

class SubscriptionCreatePage extends StatefulWidget {
  /// 订阅信息 编辑时有值
  SubscriptionList subscriptionInfo;

  SubscriptionCreatePage({Key key, this.subscriptionInfo}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _SubscriptionCreatePageState();
}

class _SubscriptionCreatePageState extends State<SubscriptionCreatePage> {
  /// 区域
  TextEditingController areaController = TextEditingController();

  /// 信息类别
  // TextEditingController categoryController = TextEditingController();

  /// 时间
  TextEditingController dateController = TextEditingController();

  /// 信息类型
  TextEditingController typeController = TextEditingController();

  /// 输入关键词
  TextEditingController inputController = TextEditingController();

  /// 订阅信息 编辑时有值
  SubscriptionList subscriptionInfo;

  /// 推荐关键词
  List<String> recommendKeywords = [];

  /// 展开或折叠自定义关键词UI
  bool isExpandCustomKeywordLayout = true;

  /// 是否已初始化
  /// 防止setState刷新的时候在initState中重新给变量赋值
  bool isInitialized = false;

  /// 信息类型
  List<CommonTagModel> _infoTypes;

  /// 订阅类别 (三级类别(types, biddingClass, industries)，不联动)
  // List<CommonTagModel> _categoryTypeDatas = [];
  // List<CommonTagModel> _categoryClassDatas = [];
  // List<CommonTagModel> _categoryIndustryDatas = [];

  Future<List<String>> _recomentKeywordsFuture;

  /// 最多可订阅关键词的个数
  int maxKeywords = 8;

  void _prepareSubscription() {
    if (subscriptionInfo.areaIds.isEmpty) {
      ToastUtils.show("请选择城市");
      return;
    }
    // if (subscriptionInfo.begin.isEmpty) {
    //   ToastUtils.show("请选择时间");
    //   return;
    // }
    if (subscriptionInfo.keyword.isEmpty) {
      ToastUtils.show("请添加订阅关键词");
      return;
    }

    _addSubscription();
  }

  /// 添加订阅
  Future _addSubscription() async {
    ApiResponse response = await ApiSubscription.addSubscript(
        id: subscriptionInfo.id,
        areaCodes: subscriptionInfo.areaIds,
        isPush: true,
        // biddingClasses: subscriptionInfo.biddingClassCode,
        // types: subscriptionInfo.typeCodes,
        // industries: subscriptionInfo.industryCodes,
        type: subscriptionInfo.type,
        keywords: subscriptionInfo.keyword,
        // time: subscriptionInfo.begin
    );
    if (response.status == Status.SUCCESS) {
      ToastUtils.show("订阅成功");
      LRouter.navigatorCtx(context).pop(true);
    }
  }

  /// 获取热门搜索关键词
  Future<List<String>> _getHotKeywords() async {
    ApiResponse response =
        await ApiSubscription.getSubscriptionHotKeywords<void>();
    List<dynamic> listDynamic = response.originalData;
    List<String> values = [];
    listDynamic.forEach((element) {
      print(element.toString());
      values.add(element.toString());
    });
    return values;
  }

  FutureBuilder<List<String>> _buildHotKeywordsBuilder() {
    return FutureBuilder(
        future: _recomentKeywordsFuture,
        // ignore: missing_return
        builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
          recommendKeywords = snapshot.data;
          if (snapshot.hasData) {
            return Wrap(children: <Widget>[
              for (String item in recommendKeywords)
                _getTagItem(item, isShowHot: true, clickCallback: () {
                  if (subscriptionInfo.keyword.length >= maxKeywords) {
                    ToastUtils.show("订阅关键词数量已达到最大限制");
                  } else {
                    if (subscriptionInfo.keyword.contains(item)) {
                      ToastUtils.show("此关键词已添加，请选择其他或自定义");
                    } else {
                      setState(() {
                        subscriptionInfo.keyword.add(item);
                      });
                    }
                  }
                })
            ]);
          } else {
            return Progressindicator();
          }
          return Container();
        });
  }

  /// 订阅类别数据
  // Future<ApiResponse<SubscriptCategoryEntity>> _getCategoryDatas() async {
  //   var response =
  //       await ApiSubscription.subscriptCategory<SubscriptCategoryEntity>();
  //   SubscriptCategoryEntity entity = response.result;
  //   _categoryTypeDatas.addAll(entity.types);
  //   _categoryClassDatas.addAll(entity.biddingClass);
  //   _categoryIndustryDatas.addAll(entity.industries);
  //   return response;
  // }

  @override
  void initState() {
    _infoTypes = [
      CommonTagModel(strId: "0",title: "全部"),
      CommonTagModel(strId: "1",title: "招标信息"),
      CommonTagModel(strId: "2",title: "中标信息")
    ];

    if (!isInitialized) {
      // _getCategoryDatas();
      _recomentKeywordsFuture = _getHotKeywords();

      if (widget.subscriptionInfo != null) {
        subscriptionInfo = widget.subscriptionInfo;

        areaController.text = getListStr(subscriptionInfo.areas);
        // List<String> cats = [
        //   ...subscriptionInfo.types,
        //   ...subscriptionInfo.biddingClasses,
        //   ...subscriptionInfo.industries
        // ];
        // categoryController.text = cats.join("-");
        dateController.text = subscriptionInfo.begin;

        for (var tag in _infoTypes){
          if (tag.strId == subscriptionInfo.type){
            typeController.text = tag.title;
            break;
          }
        }
      } else {
        /// 非编辑状态，初始化表单数据容器
        subscriptionInfo = SubscriptionList();

        String time =
            formatDate(new DateTime.now(), ['yyyy', '-', 'mm', '-', 'dd']);
        subscriptionInfo.begin = time;
        dateController.text = time;

        subscriptionInfo.type = _infoTypes[0].strId;
        typeController.text = _infoTypes[0].title;

        int areaId = (DataManager.instance.cityEntity == null
            ? null
            : DataManager.instance.cityEntity.id);
        String areaName = (DataManager.instance.cityEntity == null
            ? null
            : DataManager.instance.cityEntity.title);
        subscriptionInfo.areaIds = areaId != null ? [areaId] : null;
        areaController.text = areaName;
      }
    }

    /// 检测变量数组是否为空，防止异常
    isInitialized = true;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _initBody());
  }

  /// 关键词订阅
  Widget _initAppBar() {
    return BaseAppBar(context, Text("关键词订阅", style: FonStyle.navTextStyle()));
  }

  /// 内容题
  Widget _initBody() {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        child: Column(children: <Widget>[
          _getOptionsItem("选择区域", "请选择区域", areaController, () {
            PickerUtils.showCityPicker(context, clickCallBack: (codes, value) {
              subscriptionInfo.areaIds = [codes.last];
              areaController.text = value;
            });
          }),
          // _getOptionsItem("信息类型", "请选择信息类型", categoryController, () {
          //   PickerUtils.showArrayPicker(context, data: [
          //     _categoryTypeDatas.map((e) => e.value).toList(),
          //     _categoryClassDatas.map((e) => e.value).toList(),
          //     _categoryIndustryDatas.map((e) => e.value).toList(),
          //   ], clickCallBack: (selecteds, selectedValues) {
          //     categoryController.text = selectedValues.join("-");
          //
          //     subscriptionInfo.typeCodes.clear();
          //     subscriptionInfo.biddingClassCode.clear();
          //     subscriptionInfo.industryCodes.clear();
          //     subscriptionInfo.typeCodes
          //         .add(_categoryTypeDatas[selecteds[0]].key);
          //     subscriptionInfo.biddingClassCode
          //         .add(_categoryClassDatas[selecteds[1]].key);
          //     subscriptionInfo.industryCodes
          //         .add(_categoryIndustryDatas[selecteds[2]].key);
          //   });
          // }),
          // _getOptionsItem("开始时间", "请选择开始时间", dateController, () {
          //   PickerUtils.showDatePicker(context, clickCallback: (date, value) {
          //     String time = formatDate(value, ['yyyy', '-', 'mm', '-', 'dd']);
          //     dateController.text = time;
          //     subscriptionInfo.begin = time;
          //   });
          // }),
          _getOptionsItem("信息类型", "请选择信息类型", typeController, () {
            PickerUtils.showStringPicker(context,
                data: _infoTypes.map((e) => e.title).toList(),
                clickCallBack: (index, val) {
                  typeController.text = _infoTypes[index].title;
                  subscriptionInfo.type =  _infoTypes[index].strId;
                });
          }),

          _initHaveKeyworkds(),
          _initCustomKeyworkds(),
          _initRecommendKeyworkds(),
          _initSubmitBtn()
        ]),
      ),
    );
  }

  /// 已订阅关键词View
  Widget _initHaveKeyworkds() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(
                  top: ScreenAdapter.height(30),
                  bottom: ScreenAdapter.height(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(
                          text: "已订阅关键词",
                          style: TextStyle(
                            fontSize: ScreenAdapter.sp(30),
                            fontWeight: FontWeight.w500,
                            color: ThemeColors.colorType1,
                          ),
                          children: <TextSpan>[
                            TextSpan(
                                text: "（最多可订阅$maxKeywords个）",
                                style: TextStyle(
                                  fontSize: ScreenAdapter.sp(28),
                                  // fontWeight: FontWeight.w500,
                                  color: ThemeColors.colorType14,
                                )),
                          ],
                        )),
                    RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(
                          text: subscriptionInfo.keyword.length.toString(),
                          style: TextStyle(
                            fontSize: ScreenAdapter.sp(30),
                            fontWeight: FontWeight.w500,
                            color: ThemeColors.colorType6,
                          ),
                          children: <TextSpan>[
                            TextSpan(
                                text: " / ${maxKeywords}",
                                style: TextStyle(
                                  fontSize: ScreenAdapter.sp(28),
                                  color: ThemeColors.colorType14,
                                )),
                          ],
                        ))
                  ])),
          Wrap(children: <Widget>[
            for (String item in subscriptionInfo.keyword)
              _getTagItem(item, isShowClose: true, deleteCallback: () {
                setState(() {
                  subscriptionInfo.keyword.remove(item);
                });
              })
          ])
        ],
      ),
    );
  }

  /// 推荐关键词
  Widget _initRecommendKeyworkds() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(
                  top: ScreenAdapter.height(30),
                  bottom: ScreenAdapter.height(30)),
              child: Text("推荐关键词",
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.w500))),
          _buildHotKeywordsBuilder()
        ],
      ),
    );
  }

  /// 自定义关键词
  Widget _initCustomKeyworkds() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(
                  top: ScreenAdapter.height(30),
                  bottom: ScreenAdapter.height(15)),
              child: Text("自定义关键词",
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.w500))),
          Row(children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: ScreenAdapter.width(30)),
                decoration: BoxDecoration(
                    color: ThemeColors.colorType37,
                    borderRadius:
                        BorderRadius.circular(ScreenAdapter.width(14))),
                child: TextField(
                  controller: inputController,
                  decoration: InputDecoration(
                      hintText: "请输入关键词", border: InputBorder.none),
                  style: TextStyle(
                      color: ThemeColors.colorType4,
                      fontSize: ScreenAdapter.sp(32)),
                  textAlign: TextAlign.left,
                  maxLines: 1,
                  // enabled: false,
                  // readOnly: true,
                  autofocus: false,
                  // controller: controller,
                ),
              ),
            ),
            SizedBox(width: ScreenAdapter.width(20)),
            Container(
                width: ScreenAdapter.width(160),
                height: ScreenAdapter.height(80),
                decoration: BoxDecoration(
                    color: ThemeColors.colorType6,
                    borderRadius:
                        BorderRadius.circular(ScreenAdapter.width(14))),
                child: FlatButton(
                    onPressed: () {
                      if (subscriptionInfo.keyword.length >= maxKeywords) {
                        ToastUtils.show("订阅关键词数量已达到最大限制");
                      } else {
                        if (subscriptionInfo.keyword
                            .contains(inputController.text)) {
                          ToastUtils.show("此关键词已添加，请选择其他或自定义");
                        } else if (!isEmpty(inputController.text)) {
                          setState(() {
                            subscriptionInfo.keyword.add(inputController.text);
                          });
                          inputController.text = "";
                        }
                      }
                    },
                    child: Text("添加",
                        style: TextStyle(
                            color: ThemeColors.colorWhite,
                            fontSize: ScreenAdapter.sp(32)))))
          ])
        ],
      ),
    );
    // return ExpansionPanelList(
    //   elevation: 0,
    //   expandedHeaderPadding: EdgeInsets.zero,
    //   expansionCallback: (int index, bool isExpanded) {
    //     setState(() {
    //       isExpandCustomKeywordLayout = !isExpanded;
    //     });
    //   },
    //   children: <ExpansionPanel>[
    //     ExpansionPanel(
    //         isExpanded: isExpandCustomKeywordLayout,
    //         canTapOnHeader: false,
    //         headerBuilder: (BuildContext context, bool isExpanded) {
    //           return Padding(
    //               padding: EdgeInsets.only(
    //                   top: ScreenAdapter.height(30),
    //                   bottom: ScreenAdapter.height(30)),
    //               child: Text("自定义关键词",
    //                   style: TextStyle(
    //                       color: ThemeColors.colorType1,
    //                       fontSize: ScreenAdapter.sp(30))));
    //         },
    //         body: Row(children: <Widget>[
    //           Expanded(
    //             child: Container(
    //               padding: EdgeInsets.only(left: ScreenAdapter.width(30)),
    //               decoration: BoxDecoration(
    //                   color: ThemeColors.colorType37,
    //                   borderRadius:
    //                       BorderRadius.circular(ScreenAdapter.width(14))),
    //               child: TextField(
    //                 controller: inputController,
    //                 decoration: InputDecoration(
    //                     hintText: "请输入关键词", border: InputBorder.none),
    //                 style: TextStyle(
    //                     color: ThemeColors.colorType4,
    //                     fontSize: ScreenAdapter.sp(32)),
    //                 textAlign: TextAlign.left,
    //                 maxLines: 1,
    //                 // enabled: false,
    //                 // readOnly: true,
    //                 autofocus: false,
    //                 // controller: controller,
    //               ),
    //             ),
    //           ),
    //           SizedBox(width: ScreenAdapter.width(20)),
    //           Container(
    //               width: ScreenAdapter.width(160),
    //               height: ScreenAdapter.height(80),
    //               decoration: BoxDecoration(
    //                   color: ThemeColors.colorType6,
    //                   borderRadius:
    //                       BorderRadius.circular(ScreenAdapter.width(14))),
    //               child: FlatButton(
    //                   onPressed: () {
    //                     if (subscriptionInfo.keyword.length >= maxKeywords) {
    //                       ToastUtils.show("订阅关键词数量已达到最大限制");
    //                     } else {
    //                       if (subscriptionInfo.keyword
    //                           .contains(inputController.text)) {
    //                         ToastUtils.show("此关键词已添加，请选择其他或自定义");
    //                       } else {
    //                         setState(() {
    //                           subscriptionInfo.keyword
    //                               .add(inputController.text);
    //                         });
    //                         inputController.text = "";
    //                       }
    //                     }
    //                   },
    //                   child: Text("添加",
    //                       style: TextStyle(
    //                           color: ThemeColors.colorWhite,
    //                           fontSize: ScreenAdapter.sp(32)))))
    //         ]))
    //   ],
    // );
  }

  /// 提交按钮
  Widget _initSubmitBtn() {
    return GestureDetector(
      child: Container(
          height: ScreenAdapter.height(90),
          width: double.infinity,
          margin: EdgeInsets.symmetric(vertical: ScreenAdapter.height(50)),
          decoration: BoxDecoration(
              color: ThemeColors.colorType6,
              borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
          child: FlatButton(
              onPressed: () {
                _prepareSubscription();
              },
              child: Text("确定",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(32))))),
    );
  }

  /// 获取选项Item
  Widget _getOptionsItem(String title, String placeholder,
      TextEditingController controller, GestureTapCallback callback) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(
              top: ScreenAdapter.height(30), bottom: ScreenAdapter.height(15)),
          child: RichText(
              textAlign: TextAlign.center,
              text: TextSpan(
                text: title,
                style: TextStyle(
                  fontSize: ScreenAdapter.sp(30),
                  fontWeight: FontWeight.w500,
                  color: ThemeColors.colorType1,
                ),
                // children: <TextSpan>[
                //   TextSpan(
                //       text: "（可选）",
                //       style: TextStyle(
                //         fontSize: ScreenAdapter.sp(28),
                //         // fontWeight: FontWeight.w500,
                //         color: ThemeColors.colorType14,
                //       )),
                // ],
              )),
        ),
        Container(
          height: ScreenAdapter.height(84),
          padding: EdgeInsets.only(
              left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
          decoration: BoxDecoration(
              color: ThemeColors.colorType37,
              borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
          child: Row(
            children: [
              Expanded(
                  child: TextField(
                onTap: callback,
                decoration: InputDecoration(
                    hintText: placeholder, border: InputBorder.none),
                style: TextStyle(
                    color: ThemeColors.colorType4,
                    fontSize: ScreenAdapter.sp(32)),
                textAlign: TextAlign.left,
                maxLines: 1,
                readOnly: true,
                autofocus: false,
                controller: controller,
              )),
              Image.asset(
                RPath.imgPath + "icon_person_right_arrow.png",
                width: ScreenAdapter.width(30),
                height: ScreenAdapter.width(30),
              ),
            ],
          ),
        )
      ],
    );
  }

  /// 关键词Item
  Widget _getTagItem(String text,
      {bool isShowClose = false,
      bool isShowHot = false,
      GestureTapCallback clickCallback,
      GestureTapCallback deleteCallback}) {
    return Stack(
      children: <Widget>[
        GestureDetector(
            onTap: clickCallback,
            child: Container(
              margin: EdgeInsets.symmetric(
                  vertical: ScreenAdapter.height(10),
                  horizontal: ScreenAdapter.width(10)),
              padding: EdgeInsets.symmetric(
                  vertical: ScreenAdapter.height(15),
                  horizontal: ScreenAdapter.width(30)),
              decoration: BoxDecoration(
                  color: ThemeColors.colorType38,
                  borderRadius: BorderRadius.all(
                      Radius.circular(ScreenAdapter.width(4)))),
              child: Text(text,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: ThemeColors.colorType6,
                      fontSize: ScreenAdapter.sp(28))),
            )),
        isShowClose
            ? Positioned(
                right: 0,
                top: 0,
                child: GestureDetector(
                  onTap: deleteCallback,
                  child: Container(
                      padding: EdgeInsets.fromLTRB(ScreenAdapter.width(20), 0,
                          ScreenAdapter.width(5), ScreenAdapter.width(20)),
                      color: ThemeColors.colorTransparent,
                      child: Image.asset(RPath.imgPath + "icon_close_x.png",
                          width: ScreenAdapter.width(20),
                          height: ScreenAdapter.width(20))),
                ),
              )
            : SizedBox(),
        isShowHot
            ? Positioned(
                left: ScreenAdapter.width(10),
                top: ScreenAdapter.height(10),
                child: Container(
                    child: Image.asset(RPath.imgPath + "icon_hot.png",
                        width: ScreenAdapter.width(42),
                        height: ScreenAdapter.width(42))),
              )
            : SizedBox()
      ],
    );
  }
}
